package com.itwn.email.consumer.f_confirm;

import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class ConfirmListener {

    /**
     * 消息确认、消费者可靠性保证
     */
    @SneakyThrows
    @RabbitListener(queues = "confirm.queue")
    public void handle(String content, Channel channel, Message message) {
        try {
            int i = 4 / 0;
            System.out.println("消费者收到 confirm.queue 消息：" + content);
            // 手动应答; 参数1：消息标识符; 参数2：是否批量应答，true：批量应答，false：单个应答
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            // 获取重投标记
            Boolean redelivered = message.getMessageProperties().getRedelivered();
            System.out.println("重投标记 = " + redelivered);
            if (!redelivered) {
                // 没有重投过, 重投放入队列
                channel.basicNack(
                        message.getMessageProperties().getDeliveryTag(),false,true);
                System.out.println("没有重投过,重新投递到队列");
            } else {
                // 已经重投过，直接丢弃
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
                System.out.println("已经重投过，直接丢弃");
            }
        }
    }
}